﻿$j = $.noConflict();
OGAME = function(){

	var _getHtml = null;

	function _main(){

		const SESSION_ID = gm.url_params.session; //THIS_URL_PARAMS.session;
		const ICON_REFRESH = 'data:image/gif;base64,'+
		'R0lGODlhDAAMALMAAP//AP/vAP+/AP+vAP+fAP+PAP9gYP8vAP8QEP8AAP///wAAAAAAAAAAAAAA'+
		'AAAAACH5BAUUAAoALAAAAAAMAAwAAAQ3UEmDUkJG6jqEKNdmHQEAEKFhjeWZUCtrEohg3vhp5zgd'+
		'J6QZJhZ0ZSrAFgoh6nxCGgXskpFEAAA7';

		const GALAXY_SCAN_RANGE=10;
		const RESOURCE = 1; //3000; // lower bound

		var KK_AUTO_SUBMIT = false;
		var KK_PLANET_LIST = [];

		var KK_CHK_M = false;
		var KK_CHK_C = false;
		var KK_CHK_D = false;
		var KK_RES_M = 0;
		var KK_RES_C = 0;
		var KK_RES_D = 0;
		var KK_FLEET_BY = 0;
		var KK_FLEET_TASK = 0;
		var KK_FLEET_BATCH_TASK = 0;
		var KK_SHIP_TYPE = 0;
		var KK_AUTO_MAKE_SHIP = false;

		const FLEET_BY = {
			'ALL': 1,
			'ALL_SMALL': 2,
			'ALL_BUT_TX': 3,
			'ALL_BUT_TX_SMALL': 4,
			'ALL_BUT_TX_LARGE': 5,
			'RES_CHECK': 11,
			'RES_INPUT': 12,
			'PREVIOUS': 99
		};

		const BATCH_TASK = {
			'ONE_2_MULTI': 1,
			'MULTI_2_ONE': 2
		}

		// ---------------------------------------------------------------------------



		function getRadioValue(rdo){
			for (i in rdo) {
				if (rdo[i].checked) {
					return rdo[i].value;
				}
			}
			return '';
		}

		function markGalaxy(){
			var roles = ['inactive', 'vacation', 'noob'];
			$j.each(roles, function(i, role){
				var spans = $j('span.'+role);
				$j.each(spans, function(i, span){
					var tr = span.parentNode.parentNode;
					if(tr.nodeName == 'TR'){
						$j(tr).addClass(role);
					}
				});
			});
		}

		function galaxy(){
			markGalaxy();

			function spy(galaxy, system, planet){
				//doit(order, galaxy, system, planet, planettype, shipcount)
				var url = 'index.php?ajax=1&page=flottenversand&session='+SESSION_ID;
				$j.post(url, {
					galaxy:	galaxy,
					system:	system,
					planet: planet,
					order: 6,
					planettype: 1,
					reply: 'short',
					rndval: '1234567' + gm.Utils.hash(6),
					session: SESSION_ID,
					shipcount: 1,
					speed: 10
				}, function(data){
					var results = data.split(' ');
					var msg='';
					switch(parseInt(results[0])){
						case 600:
							msg = 'ok';
							break;
						case 603:
							msg = '新手保護';
							break;
						case 605:
							msg = '假期模式';
							break;
						case 611:
							msg = '無間諜衞星';
							break;
						case 612:
							msg = '艦隊已滿';
							break;
						case 614:
							msg = '無此星球';
							break;
					}
					$j('#fleetstatusrow').get(0).style.display = '';
					var t = $j('#fleetstatustable').get(0);
					$j(t).prepend('<tr><td>間諜: '+
											 galaxy + ':' + system + ':' + planet +
											 '</td><td>' +
											 msg + ' (' + data + ')' +
											 '</td></tr>');
				});
			}

			var system = parseInt($j('input[name="system"]').get(0).value);
			var b = $j('input[type="submit"]').get(0);
			b.parentNode.innerHTML += ' <input type="radio" name="rdo_range" value="beginend" CHECKED>'+
																	'<input id="s_begin" type="text" size=3 value="'+(system-GALAXY_SCAN_RANGE)+'">~'+
																	'<input id="s_end" type="text" size=3 value="'+(system+GALAXY_SCAN_RANGE)+'">'+
																' <input type="radio" name="rdo_range" value="plusminus" >'+
																	'+/-<input id="s_plusminus" type="text" size=2 value="'+GALAXY_SCAN_RANGE+'">';
			// 加入scan按鈕
			$j('#s_plusminus').after('<a id="scanglaxy" href="#"> scan </a>');
			$j('a#scanglaxy').click(function(){
				scanGalaxy();
			});
			$j('#scanglaxy').after('<br><input id="spider_xyz" size="50" value="213_10,213_12">' +
				'<a id="spider" href="#">間諜</a>'
			);
			$j('a#spider').click(function(){
				$j.each( $j('#spider_xyz').val().split(','), function(i,t){
					var xyz = $j.trim(t).split('_');
					gm.log('xyz=[{0}]', xyz);
					switch(xyz.length){
						case 2:
							spy(1,parseInt(xyz[0].replace(/^0+/,'')),parseInt(xyz[1].replace(/^0+/,'')));
							break;
						case 3:
							spy(parseInt(xyz[0].replace(/^0+/,'')),parseInt(xyz[1].replace(/^0+/,'')),parseInt(xyz[2].replace(/^0+/,'')));
							break;
					}
				});
			});

			$j('#galaxy_form').after('<div id="GALAXY_TD" style="display:block;">DF:</div>');
		}

		function scanGalaxy(){
			//http://uni4.ogame.tw/game/index.php?page=galaxy&no_header=1&session=49a18119425f
			var url = 'http://'+document.location.host+'/game/index.php?page=galaxy&no_header=1&session='+SESSION_ID+'&galaxyLeft=dr&system=';

			// check selected option
			var rdo = $j('input[name="rdo_range"]');
			gm.log(getRadioValue(rdo));
			if(getRadioValue(rdo)=='plusminus'){
				var system = parseInt($j('input[name="system"]').get(0).value);
				var newScanRange = parseInt($j('#s_plusminus').get(0).value);
				$j('#s_begin').get(0).value = system-newScanRange;
				$j('#s_end').get(0).value = system+newScanRange;
			}

			var s1 = parseInt($j('#s_begin').get(0).value);
			var s2 = parseInt($j('#s_end').get(0).value);
			gm.log('{0}~{1}', s1, s2);

			function submitAjax(i){
				var newUrl = url+i;
				$j.get(newUrl, function(html){
					ajaxOnScanGalaxy(gm.Html.getHtmlBody(html), i, newUrl);
				});
			}

			for(var i=s1; i<=s2; i++){
				if(i<0) continue;
				submitAjax(i);
			}
		}

		function ajaxOnScanGalaxy(html, system, url){
			gm.log('ajaxOnScanGalaxy(): {0}', system);

			var galaxy = $j('input[name="galaxy"]').get(0).value;
			var div = gm.Dom.insertHddenHtml(html);
			try{
				var ths = gm.Dom._x('//div[@id="'+div.id+'"]//tr/th[5]');

				var res = [];
				$j.each(ths, function(i, th){
					if(th.innerHTML.search('<img')<=0) return;	// 沒有廢墟=>跳過

					// check how much resource here
					var a = th.childNodes[1];
					//gm.log(a.innerHTML);
					var s = a.getAttribute('onmouseover').match(/<table>.*<\/table>/gi)[0];
					//gm.log(s);

					// parse html
					var d = gm.Dom.insertHddenHtml(s);
					gm.log('d.id={0}', d.id);
					try{
						//var rths = gm.Dom._x('//div[@id="'+d.id+'"]//th[2]');
						var rths = $j('tr th:nth-child(2)', d);	// 從1開始算, 要加上父節點tr
						//gm.log(rths);
						var metal = parseInt(rths[0].innerHTML.toString().removeDot());
						var crystal = parseInt(rths[1].innerHTML.toString().removeDot());
						gm.log('[{0}:{1}:{2}] = ({3}, {4})',
									galaxy, system, (i+1), metal, crystal);
						var r = metal+crystal;
						if(r>=RESOURCE){
							res.push({
								planet: i+1,
								resource: r
							})
						}
					}finally{
						$j(d).remove();
					}

				});

				// havest the resource: doit(8, galaxy, system, plant, 2, hval);
				// where hval is number of ships, every ship can carry 20,000 resource units
				$j.each(res, function(index, r){
					var recyclers = Math.ceil(r.resource/20000);
					var color='#0f0';	// green
					var size = 11;
					if(recyclers>5){
						color = '#f00';	// red
						size = 19;
					}else if(recyclers>1){
						color = '#ff0';	// yellow
						size = 15;
					}

					$j('#GALAXY_TD').get(0).innerHTML += '<span style="font-size:'+size+'px;"><a target="_blank" href="'+url+'">'+
							system+ ':' + r.planet +
							'</a>'+
							'(<a href="#" style="color:'+color+' !important;" onclick="'+
								'doit(8,'+galaxy+','+system+','+r.planet+',2,'+recyclers+');'+
								'this.style.display=\'none\';">'+
								recyclers + ':' + r.resource + '</a>)</span>, ';
				});

			}finally{ $j(div).remove(); }
		}

		function getCookies(){
			// 讀取cookie
			KK_AUTO_MAKE_SHIP = ($j.cookie('KK_AUTO_MAKE_SHIP')=='1');
			$j('#KK_AUTO_MAKE_SHIP').get(0).checked = KK_AUTO_MAKE_SHIP;

			KK_SHIP_TYPE = ($j.cookie('KK_SHIP_TYPE')? parseInt($j.cookie('KK_SHIP_TYPE')): 0);
			$j('#KK_SHIP_TYPE').get(0).value = KK_SHIP_TYPE;

			KK_AUTO_SUBMIT = ($j.cookie('KK_AUTO_SUBMIT')=='1');
			$j('#KK_AUTO_SUBMIT').get(0).checked = KK_AUTO_SUBMIT;

			var s = $j.cookie('KK_PLANET_LIST');
			if(s && s.length>0){
				KK_PLANET_LIST = s.split(',');
			}

			KK_CHK_M = ($j.cookie('KK_CHK_M')=='1');
			$j('#KK_CHK_M').get(0).checked = KK_CHK_M;
			KK_CHK_C = ($j.cookie('KK_CHK_C')=='1');
			$j('#KK_CHK_C').get(0).checked = KK_CHK_C;
			KK_CHK_D = ($j.cookie('KK_CHK_D')=='1');
			$j('#KK_CHK_D').get(0).checked = KK_CHK_D;


			KK_RES_M = ($j.cookie('KK_RES_M')? parseInt($j.cookie('KK_RES_M'))*1000: 0);
			$j('#KK_RES_M').get(0).value = KK_RES_M/1000;
			KK_RES_C = ($j.cookie('KK_RES_C')? parseInt($j.cookie('KK_RES_C'))*1000: 0);
			$j('#KK_RES_C').get(0).value = KK_RES_C/1000;
			KK_RES_D = ($j.cookie('KK_RES_D')? parseInt($j.cookie('KK_RES_D'))*1000: 0);
			$j('#KK_RES_D').get(0).value = KK_RES_D/1000;


			KK_FLEET_BY = ($j.cookie('KK_FLEET_BY')? parseInt($j.cookie('KK_FLEET_BY')): 0);
			$j('#KK_FLEET_BY').get(0).value = KK_FLEET_BY;
			if(KK_FLEET_BY==FLEET_BY.RES_INPUT){
				$j('#divRes').show();
				$j('#divCheckRes').hide();
			}else{
				$j('#divRes').hide();
				$j('#divCheckRes').show();
			}

			KK_FLEET_TASK = ($j.cookie('KK_FLEET_TASK')? parseInt($j.cookie('KK_FLEET_TASK')): 0);
			$j('#KK_FLEET_TASK').get(0).value = KK_FLEET_TASK;

			KK_FLEET_BATCH_TASK = ($j.cookie('KK_FLEET_BATCH_TASK')? parseInt($j.cookie('KK_FLEET_BATCH_TASK')): 0);
			$j('#KK_FLEET_BATCH_TASK').get(0).value = KK_FLEET_BATCH_TASK;
		}

		function init(){
			// 取得星球/坐標
			MyPlanets.init();

			// 改標題
			var ss = document.title.split(' ');
			if(ss.length>0)
				document.title = ss[0].replace('ni', '');	// Uni4 -> U4

			try{
				// remove ad
				$j($j('tr.header').get(0).childNodes[5]).remove();

				// 設定內文區高度
				//$j('#content').get(0).style.height = ($j('body').get(0).scrollHeight - $j('#header_top').get(0).clientHeight) + 'px';
				$j('#content').get(0).style.height = ($j('body').get(0).scrollHeight - $j('table.header', '#header_top').get(0).clientHeight) + 'px';
			}catch(e){
				gm.log(e);
			}

			// 左側選單圖片取代為分隔線
			$j.each( $j('img', 'div#menu'), function(i, img){
				$j(img).replaceWith('<hr class="sep_line">');
			});

			// 加入造船選單
			var a = $j('a[href*="page=buildings"][href*="mode=Flotte"]').get(0);
			if(a){
				// ----------------------------------------------------------
				// 船艦類型
				$j(a).after('<br><select id="KK_SHIP_TYPE">'+
					'<option value="0">(船艦類型)</option>'+
					'<option value="202">小運</option>'+
					'<option value="203">大運</option>'+
					'<option value="-1">----------</option>'+
					'<option value="204">輕戰機</option>'+
					'<option value="205">重戰機</option>'+
					'<option value="206">巡洋艦</option>'+
					'<option value="207">戰列艦</option>'+
					'<option value="211">導彈艦</option>'+
					'<option value="215">戰巡艦</option>'+
					'<option value="213">毀滅者</option>'+
					'<option value="-1">----------</option>'+
					'<option value="208">殖民船</option>'+
					'<option value="209">回收船</option>'+
					'<option value="-1">----------</option>'+
					'<option value="210">間諜衞星</option>'+
					'<option value="212">太陽衞星</option>'+
					'</select>'
				);
				// set event handler
				$j('#KK_SHIP_TYPE').change(function(){
					// set cookie
					gm.log('#KK_SHIP_TYPE.value={0}', this.value);
					$j.cookie('KK_SHIP_TYPE', this.value);
				});

				// ----------------------------------------------------------
				// 自動造船
				$j(a).after('<br><input type="checkbox" id="KK_AUTO_MAKE_SHIP">自動造船');
				// set event handler
				$j('#KK_AUTO_MAKE_SHIP').change(function(){
					// set cookie
					$j.cookie('KK_AUTO_MAKE_SHIP', (this.checked? 1: 0));
				});

			} // if(a)

			// 加入資源選單
			a = $j('a[href*="page=flotten1"]').get(0);
			if(a){
				// ----------------------------------------------------------
				$j(a).after('<div id="divRes">'+
					'金屬: <input id="KK_RES_M" size="4" style="text-align:right;"> K<br>'+
					'晶體: <input id="KK_RES_C" size="4" style="text-align:right;"> K<br>'+
					'重氫: <input id="KK_RES_D" size="4" style="text-align:right;"> K'+
					'</div>'
				);
				$j('#divRes').hide();
				// set event handler
				$j('input[id*="KK_RES_"]').change(function(){
					// set cookie
					$j.cookie(this.id, this.value);
					gm.log(this.id + '={0}', this.value);
				});

				// ----------------------------------------------------------
				$j(a).after('<div id="divCheckRes">'+
					'<input type="checkbox" id="KK_CHK_M">M'+
					'<input type="checkbox" id="KK_CHK_C">C'+
					'<input type="checkbox" id="KK_CHK_D">D'+
					'</div>'
				);
				// set event handler
				$j('input[id*="KK_CHK_"]').change(function(){
					$j.cookie(this.id, (this.checked? 1: 0));	// set cookie
					gm.log(this.id + '={0}', (this.checked? 1: 0));
				});

				// ----------------------------------------------------------
				// 單一艦隊任務選單
				$j(a).after('<br><select id="KK_FLEET_TASK">'+
					'<option value="0">(艦隊任務)</option>'+
					'<option value="1">攻擊 Att</option>'+
					'<option value="3">運輸 Tx</option>'+
					'<option value="4">派遣 Dep</option>'+
					'<option value="6">間諜 Spy</option>'+
					'<option value="7">殖民 Clon</option>'+
					'<option value="8">回收 Harv</option>'+
					'<option value="15">探索 Exp</option>'+
					'</select>'
				);
				// set event handler
				$j('#KK_FLEET_TASK').change(function(){
					// set cookie
					gm.log('#KK_FLEET_TASK.value={0}', this.value);
					$j.cookie('KK_FLEET_TASK', this.value);
				});

				// ----------------------------------------------------------
				// 艦隊數目選單
				$j(a).after('<br><select id="KK_FLEET_BY">'+
					'<option value="0">(艦隊數目)</option>'+
					'<option value="'+FLEET_BY.ALL+'">所有船艦</option>'+
					'<option value="'+FLEET_BY.ALL_BUT_TX+'">留大小運</option>'+
					'<option value="'+FLEET_BY.ALL_BUT_TX_SMALL+'">只留小運</option>'+
					'<option value="'+FLEET_BY.ALL_BUT_TX_LARGE+'">只留大運</option>'+
					'<option value="'+FLEET_BY.ALL_SMALL+'">全部小運</option>'+
					'<option value="-1">----------</option>'+
					'<option value="'+FLEET_BY.RES_CHECK+'">勾選資源</option>'+
					'<option value="'+FLEET_BY.RES_INPUT+'">輸入資源</option>'+
					'<option value="'+FLEET_BY.PREVIOUS+'">同前</option>'+
					'</select>'
				);
				// set event handler
				$j('#KK_FLEET_BY').change(function(){
					KK_FLEET_BY = parseInt(this.value);
					// set cookie
					gm.log('#KK_FLEET_BY.value={0}', KK_FLEET_BY);
					$j.cookie('KK_FLEET_BY', KK_FLEET_BY);
					if(KK_FLEET_BY==FLEET_BY.RES_INPUT){
						$j('#divRes').show();
						$j('#divCheckRes').hide();
					}else{
						$j('#divRes').hide();
						$j('#divCheckRes').show();
					}

					if(KK_FLEET_BY != FLEET_BY.RES_CHECK){	// uncheck resources
						$j('#KK_CHK_M').get(0).checked = false;
						$j('#KK_CHK_C').get(0).checked = false;
						$j('#KK_CHK_D').get(0).checked = false;
						$j.cookie('KK_CHK_M', 0);
						$j.cookie('KK_CHK_C', 0);
						$j.cookie('KK_CHK_D', 0);
					}
				});

				// ----------------------------------------------------------
				// 批次艦隊任務選單
				$j(a).after('<br><select id="KK_FLEET_BATCH_TASK">'+
				  '<option value="-1">(任務型態)</option>'+
					'<option value="0">單一(1~1)</option>'+
					'<option value="'+BATCH_TASK.ONE_2_MULTI+'">批次(1~*)</option>'+
					'<option value="'+BATCH_TASK.MULTI_2_ONE+'">批次(*~1)</option>'+
					'</select>'
				);
				// set event handler
				$j('#KK_FLEET_BATCH_TASK').change(function(){
					// set cookie
					gm.log('#KK_FLEET_BATCH_TASK.value={0}', this.value);
					$j.cookie('KK_FLEET_BATCH_TASK', this.value);
				});

				// ----------------------------------------------------------
				// 自動發送
				$j(a).after('<br><input type="checkbox" id="KK_AUTO_SUBMIT">自動發送');
				// set event handler
				$j('#KK_AUTO_SUBMIT').change(function(){
					// set cookie
					$j.cookie('KK_AUTO_SUBMIT', (this.checked? 1: 0));
				});

			} // if(a)

			// 加入(+)開啟新視窗
			$j.each( $j('a', 'div#menu'), function(i, a){
				if(i<2 || a.target=='_blank' || a.href=='#' || a.onclick) return;
				//gm.log( 'a.target={0}', $j(a).attr('target') );
				$j(a).after('<a target="_blank" href="'+ a.href +'"> +</a>');
			});

			// 需最後做
			getCookies();

		}

		var MyPlanets = function(){
			var _names = [];
			var _coords = [];	// ['[1:202:3]', '[1:202:5]', ...]
			return {
				init: function(){
					// get planet name/coord pairs
					var options = $j('td.header option');
					$j.each(options, function(i, opt){	//DiKuC [1:199:7]
						var arr = opt.textContent.split('[');
						_names.push($j.trim(arr[0]));
						_coords.push('['+$j.trim(arr[1]));
					});
				},

				// 傳回名稱字串陣列
				names: function(){
					return _names;
				},

				// 傳回坐標字串陣列
				coords: function() {
					return _coords;
				},

				// 傳回index坐標物件
				coord: function(i){
					if(!_coords[i]) return null;
					var cArr = _coords[i].replace(/(\[|\])/g, '').split(':');	// '[1:200:3]'
					return {
						type: '1',	// 1-星球; 2-DF; 3-Moon
						galaxy: cArr[0],
						system: cArr[1],
						planet: cArr[2]
					};
				},

				// 字串轉為坐標物件
				stringToCoord: function(s){	// 字串- '1,1:200:10'
					var rx = /\d+,\d+\:\d+\:\d+/g;
					if(!rx.test(s))	return null;
					var arr = s.split(',');
					var cArr = arr[1].split(':');
					return {
						type: arr[0],	// 1-星球; 2-DF; 3-Moon
						galaxy: cArr[0],
						system: cArr[1],
						planet: cArr[2]
					};

				},

				// 比較二組坐標是否全等
				coordCompare: function(c1, c2){
					try{
							return ( c1.type==c2.type &&
								c1.galaxy==c2.galaxy &&
								c1.system==c2.system &&
								c1.planet==c2.planet
							);
					}catch(ex){
						return false;
					}
				},

				getNameByCoord: function(c){
					for(var i=0; i<_coords.length; i++){
						if(_coords[i]==c)	return _names[i];
					}
					return '';
				}
			};
		}();


		function overview(){
			// check & email alarm if attack
			var atk = $j('.attack').get(0);
			if(atk){
				var uni = document.location.host.split('.')[0];
				var url = 'http://efms.emome.net/web/map/sendmail.asp?priority=1' +
									'&fromMail=ogame@ogame.org' +
									'&toMail=arphen@cht.com.tw' +
									'&subject=[ogame] '+uni+' alarm' +
									'&body=' + atk.innerHTML;
									//'&body=' + uni;
				_getHtml(url, function(html){
					gm.log(html);
				});
			}

			// append a row
			$j($j('tbody').get(5)).append('<tr><th id="myInfo" colspan="4">Total</th></tr>');

			// 簡化艦隊列表
			$j.each( $j('span.flight, span.return, span.holding'), function(i, span){
				for(var j=0; j<span.childNodes.length; j++){
					var el = span.childNodes[j];
					if(el.nodeName!='A'){
						el.textContent = ' | ';
					}
				}
			});

			// 以名稱取代坐標
			$j.each( $j('span.flight a, span.return a, span.holding a'), function(i, a){
				var name = MyPlanets.getNameByCoord($j.trim(a.innerHTML));
				if(name != ''){
					a.innerHTML = name;
				}
			});

			// 處理目前星球: 將圖片取代為文字
			var res = getResources();
			var sel = $j('select').get(0);
			var url = 'http://' + document.location.host + sel.options[sel.selectedIndex].value;
			var txt = $j('<b>').get(0);
			txt.innerHTML = sel.options[sel.selectedIndex].textContent.replace('[','<br>[') +
				'<br><a href="'+url+'">' + res.toString().replace(/\,/g, '<br>') + '</a>';
			$j( $j('th[colspan="2"] img').get(0) ).replaceWith( $j(txt) );

			// 修改 rename 連結
	 		var a = gm.Dom._x('//a[contains(@href,"page=renameplanet")]');	 // fail to use $j()
			//var a = $j('a[href*="page=renameplanet")]');	 // fail to use $j()
			var planetA = (a.length==2? a[1]: a[0]);
			if(a.length==2){
				a[1].href = a[0].href;
			}

			// add form to delete/rename planet
			var form = $j('<form>').get(0);
			form.setAttribute('method', 'post');
			form.setAttribute('action', planetA.href);
			form.innerHTML = '<input type="text" name="newname" size="25" maxlength="20">' +
				'<input type="submit" name="aktion" value="rename">' +
				'<input type="submit" name="aktion" value="abandon colony" alt="abandon the colony">';
			$j(planetA.nextSibling).after($j(form));


			// mark busy planet
			$j.each( $j('br + center'), function(i, c){
				var s = c.textContent.trim();
				if(s.length!=2 && s.indexOf('free')<0){
					$j(c.parentNode).addClass('busy');
				}
			});

			// get all planets' resources
			overview_all();

		}


		function overview_all(){
			if(/page\=overview/.test(gm.url) == false)		return;

			// get glaxy resources using ajax
			function submitAjax(url, cp){
				$j.get(url,	function(html){
					processGlaxyInfo(gm.Html.getHtmlBody(html), cp);
				});
			}

			$j.each( $j('a[href*="page=overview"]'), function(i, a){
				$j(a.parentNode).addClass('ogame_glaxy_info');
				var url = a.href;
				var cp = gm.Utils.getUrlParams(url).cp;
				if(cp){
					submitAjax(url, cp);
				}
			});

			// after that, query current glaxy
			var sel = $j('select').get(0);
			var url = 'http://' + document.location.host + sel.options[sel.selectedIndex].value;
			$j.get(url);

		}

		var TOTAL_RESOURCE = [0,0,0];		// metal, crystal, deuterium
		function cacuTotalResources(res){
			$j.each(res, function(i, r){
				TOTAL_RESOURCE[i] += parseInt(r.removeDot());
			});

			var th = $j('#myInfo').get(0);
			$j(th).html('Total Metal: <font color="#f1531e">'+TOTAL_RESOURCE[0].addDot()+'</font>'+
				'<br>Total Crystal: <font color="#54b0dc">'+TOTAL_RESOURCE[1].addDot()+'</font>'+
				'<br>Total Deuterium: <font color="#9aaccb">'+TOTAL_RESOURCE[2].addDot()+'</font>'
			);
		}

		function processGlaxyInfo(html, cp){
			var div = gm.Dom.insertHddenHtml(html);
			try{
				var res = getResources(div);
				cacuTotalResources(res);
				gm.log('MCD = {0}', res.toString());
				gm.log('total = {0}', TOTAL_RESOURCE.toString());
				var resValue = res.toString().replace(/\,/g, '<br>');

				var a_glaxy = $j('a[href*="cp='+cp+'"]').get(0);
				if(a_glaxy){
					var th = a_glaxy.parentNode;

					var i = th.innerHTML.indexOf('</a>');
					var txt = th.innerHTML.substring(i+4, th.innerHTML.length);

					var sel = $j('select', div).get(0);
					th.innerHTML = sel.options[sel.selectedIndex].textContent.replace('[','<br>[') +
						'<br><a href="'+ a_glaxy.href +'">' + resValue + '</a>' + txt;
				}
			}finally{ $j(div).remove(); }
		}

		function messages(){
			// set list menu
			$j.each( $j('select[name*="deletemessages"]'), function(i, s){
				s.options[1].selected = 'true'; // delete unmarked messages
			});

			// mark combat reports
			$j.each( $j('span[class*="combatreport"]'), function(i, s){
				var tr = s.parentNode.parentNode.parentNode;
				$j('input', tr).get(0).checked = true;
			});
		}

		function getDT(){
			var d = new Date();
			var dt = {};
			dt.M = d.getMonth()+1;
			dt.d = d.getDate();
			dt.h = d.getHours();
			dt.m = d.getMinutes();
			dt.s = d.getSeconds();
			return dt;
		}

		function formatDT(ogameDt){	// Tue Dec 4 10:09:11
			var MONTH = {
				'Jan':1,
				'Feb':2,
				'Mar':3,
				'Apr':4,
				'May':5,
				'Jun':6,
				'July':7,
				'Aug':8,
				'Sep':9,
				'Oct':10,
				'Nov':11,
				'Dec':12
			};
			s = ogameDt.split(' ');		// [Tue,Dec,4,10:09:11]
			var dt = {};
			dt.M = MONTH[s[1]];
			dt.d = parseInt(s[2]);
			s = s[3].split(':');
			dt.h = parseInt(s[0]);
			dt.m = parseInt(s[1]);
			dt.s = parseInt(s[2]);
			return dt;
		}

		// addDate(5, 5, "2004/12/1 00:00:00")
		function addDate(type, interval, dtDate){
			var date = new Date(dtDate);
			switch(type){
				case DT_TYPE.YEAR ://年
					date.setYear(date.getYear() + interval);
					break;
				case DT_TYPE.QTR ://季度
					date.setMonth(date.getMonth() + (interval * 3) );
					break;
				case DT_TYPE.MONTH ://月
					date.setMonth(date.getMonth() + interval);
					break;
				case DT_TYPE.DAY ://天
					date.setDate(date.getDate() + interval);
					break;
				case DT_TYPE.HOUR ://时
					date.setHours(date.getHours() + interval);
					break;
				case DT_TYPE.MINUTE ://分
					date.setMinutes(date.getMinutes() + interval);
					break;
				case DT_TYPE.SECOND ://秒
					date.setSeconds(date.getSeconds() + interval);
					break;
				default:
			}
			//return date.getYear() +'-' + (date.getMonth()+1) + '-' +date.getDate()+ ' ' +
			//return (date.getMonth()+1) + '/' + date.getDate() + ' ' +
			//				date.getHours() +':' + date.getMinutes() + ':' + date.getSeconds();
			return date.format('M/d h:m:s');
		}

		function addDT(ogameDt, diff){		// diff(m)
			var st = formatDT(ogameDt);
			var s = '2007/'+st.M+'/'+st.d+' '+st.h+':'+st.m+':'+st.s;
			return addDate(2, diff, s);
		}

		function ajaxOnGetServerTime(html){
			var s, lt=getDT();

			var div = gm.Dom.insertHddenHtml(html);
			try{
				s = $j('#content table tr th', div).filter(function(i){
					return this.textContent.match(/ \d+ \d+:\d+:\d+/);
				}).get(0).textContent;
				gm.log('server time = {0}', s);
			}finally{ $j(div).remove(); }

			// server time
			var st = formatDT(s);
			var totalsm = st.h*60+st.m

			// local minute
			var totallm = lt.h*60 + lt.m;

			// compare
			var diff = ((st.M==lt.M && st.d==lt.d)? (totallm-totalsm) : (1440+totallm-totalsm));
			gm.log('diff={0}(m)', diff);

			// change ogame time
			$j.each($j('th'), function(i, th){
				if(!th.textContent.match(/ \d+ \d+:\d+:\d+/))	return;
				//th.innerHTML += '<br>'+ addDT(th.textContent, diff);
				th.innerHTML = addDT(th.textContent, diff);
			});

		}

		function getResources(container){
			var res = [];	// metal, crystal, Deuterium
			$j.each( $j('tr.header font', container), function(i, f){
				if(i>=5 && i<=7)
					res.push(f.textContent);
			});
			return res;
		}

		function adjustTime(){
			// 1. get server time from overview page
			var url = 'http://'+document.location.host+'/game/index.php?page=overview&session='+SESSION_ID;
			gm.log(url);
			$j.get(url,	function(html){
				ajaxOnGetServerTime(html);
			});
		}

		function refreshKukiPlanetList(){
			// 取得所有check的資料
			KK_PLANET_LIST = [];	// reset
			$j.each($j('input[planetId]'), function(i, chk){
				if(chk.checked)		KK_PLANET_LIST.push(i);
			});
			// set cookie
			$j.cookie('KK_PLANET_LIST', KK_PLANET_LIST.toString());
			gm.log('KK_PLANET_LIST={0}', KK_PLANET_LIST.toString());
		}

		function showPlanetList(tbody){
			// 列出星球清單
			gm.log('KK_PLANET_LIST={0}', KK_PLANET_LIST.toString());
			tbody.innerHTML = '<tr><td class="c" id="planetList" colspan="8"></td></tr> ' + tbody.innerHTML;
			var planetList = $j('#planetList').get(0);
			$j(planetList).append('<input type="button" id="btnCheckAll"   tag="1" value="全選">');
			$j(planetList).append('<input type="button" id="btnUnCheckAll" tag="0" value="全不選">');
			$j('#btnCheckAll, #btnUnCheckAll').click(function(){
				var tag = $j(this).attr('tag');
				gm.log('tag={0}', tag);
				$j.each( $j('input[planetId]'), function(i, chk){
					chk.checked = (tag=='1');
				});
				refreshKukiPlanetList();
			});

			function isCheckedPlanet(id){
				for(var i=0; i<KK_PLANET_LIST.length; i++){
					var val = parseInt(KK_PLANET_LIST[i]);
					if(id==val)	return true;
					if(id<val) return false;
				}
				return false;
			}
			$j.each(MyPlanets.names(), function(i, p){
				$j(planetList).append('<input type="checkbox" planetId="'+i+'" '+(isCheckedPlanet(i)?'checked':'')+'>'+p);
			});
			$j('input[planetId]').change(refreshKukiPlanetList);
		}

		// return: true-ok; false-fleet not enough
		function setFleetsByResource(total){
			// 先算小運
			var needSmallShip = Math.ceil(total/5000);
			var maxship202 = $j('input[name="maxship202"]').get(0);
			if(maxship202){
				var maxSmallShip = parseInt(maxship202.value);
				if(needSmallShip <= maxSmallShip){
					$j('input[name="ship202"]').get(0).value = needSmallShip;
					total = 0;	// 全被小運載完了
				}else{
					$j('input[name="ship202"]').get(0).value = maxSmallShip;
					total -= (maxSmallShip*5000);	// 扣除小運載送量
				}
			}

			// 有必要再算大運
			if(total>0){
				if($j('input[name="ship203"]').get(0)){
					var needLargeShip = Math.ceil(total/25000);
					var maxship203 = $j('input[name="maxship203"]').get(0);
					if(maxship203){
						maxLargeShip = parseInt(maxship203.value);
						$j('input[name="ship203"]').get(0).value = needLargeShip;
						if(needLargeShip > maxLargeShip)
							total -= maxLargeShip*24000;
						else
							total=0;
					}
				}
			}

			return total;
		}

		var TX_RES_TOTAL=0;
		function setFleets(){
			// 設定艦隊數目
			var inputs = $j('input');
			switch(KK_FLEET_BY){
				case FLEET_BY.PREVIOUS:{	// 同前
					// 先前船艦數
					$j.each( $j('input[name^="ship"]'), function(i, ship){
						var n = $j.cookie('KK_'+ship.name);
						if(n){
							ship.value = n;
						}
					});
				} break;
				case FLEET_BY.ALL:{	// 全部艦隊
					$j.each(inputs, function(i, input){
						if(input.value==0){
							try{
								input.value = $j('input[name="max'+input.name+'"]').get(0).value;
							}catch(e){ gm.log(e); }
						}
					});
				} break;
				case FLEET_BY.ALL_BUT_TX:{	// 留大小運
					$j.each(inputs, function(i, input){
						if(input.value==0){
							try{
								input.value = $j('input[name="max'+input.name+'"]').get(0).value;
							}catch(e){ gm.log(e); }
						}
						if(input.name=='ship202'){ // 保留小運數
						  if(parseInt(input.value)>50)
							  input.value = parseInt(input.value)-50;
							else
							   input.value=0;
						}else if(input.name=='ship203'){ // 保留大運數
						  var ship202 = $j('input[name="maxship202"]').val();
						  if(ship202 && parseInt(ship202)>=50) return;
						  var ship203 = Math.ceil((50-parseInt(ship202))/5);  // 扣除小運, 留下的大運數
						  if(parseInt(input.value)>ship203)
						    input.value = parseInt(input.value)-ship203;
						  else
						     input.value=0;
						}
					});
				} break;
				case FLEET_BY.ALL_BUT_TX_SMALL:{	// 留小運
					$j.each(inputs, function(i, input){
						if(input.value==0){
							try{
								input.value = $j('input[name="max'+input.name+'"]').get(0).value;
							}catch(e){ gm.log(e); }
						}
						if(input.name=='ship202'){ // 保留小運數
						  if(parseInt(input.value)>50)
							  input.value = parseInt(input.value)-50;
							else
							   input.value=0;
						}
					});
				} break;
				case FLEET_BY.ALL_BUT_TX_LARGE:{	// 留大運
					$j.each(inputs, function(i, input){
						if(input.value==0){
							try{
								input.value = $j('input[name="max'+input.name+'"]').get(0).value;
							}catch(e){ gm.log(e); }
						}
						if(input.name=='ship203'){ // 保留大運數
						  if(parseInt(input.value)>10)
						    input.value = parseInt(input.value)-10;
						  else
						     input.value=0;
						}
					});
				} break;
				case FLEET_BY.ALL_SMALL:{	// 全部小運
					maxShip('ship202');
				} break;
				case FLEET_BY.RES_CHECK:{ // 勾選資源
					if(KK_CHK_M || KK_CHK_C || KK_CHK_D) {	// 足夠載運資源即可
						// 取得資源量
						var res = getResources();
						gm.log('MCD = {0}', res.toString());

						// 計算總資源數
						TX_RES_TOTAL = 0;
						if(KK_CHK_M) TX_RES_TOTAL += parseInt(res[0].removeDot());
						if(KK_CHK_C) TX_RES_TOTAL += parseInt(res[1].removeDot());
						if(KK_CHK_D) TX_RES_TOTAL += parseInt(res[2].removeDot());

						// 計算運輸艦數
						var rest = setFleetsByResource(TX_RES_TOTAL);
						gm.log('rest={0}', rest);
					}
				} break;
				case FLEET_BY.RES_INPUT: {	// 輸入資源
					// 取得資源量
					var res = getResources();
					gm.log('MCD = {0}', res.toString());

					// 計算總資源數
					var m = parseInt(res[0].removeDot());
					var c = parseInt(res[1].removeDot());
					var d = parseInt(res[2].removeDot());

					// 要載送的資源總數
					TX_RES_TOTAL = (KK_RES_M>=m? m: KK_RES_M);
					TX_RES_TOTAL += (KK_RES_C>=c? c: KK_RES_C);
					TX_RES_TOTAL += (KK_RES_D>=d? d: KK_RES_D);
					gm.log('資源 TX_RES_TOTAL={0}', TX_RES_TOTAL);

					// 計算運輸艦數
					var rest = setFleetsByResource(TX_RES_TOTAL);
					gm.log('rest={0}', rest);

					// 計算真正載運量
					var m_tx, c_tx, d_tx;
					m_tx = (KK_RES_M>=m? m: KK_RES_M);
					c_tx = (KK_RES_C>=c? c: KK_RES_C);
					d_tx = (KK_RES_D>=d? d: KK_RES_D);
					if(rest>0){	// 船不夠載
						var totalTx = TX_RES_TOTAL-rest;	// 可承載之總運量
						m_tx = (KK_RES_M>=m? m: KK_RES_M);
						if(m_tx>totalTx){	// 超過了
							m_tx = totalTx;
							totalTx=0;
						}else{	// 還夠載
							totalTx-=m_tx;
						}
						c_tx = (KK_RES_C>=c? c: KK_RES_C);
						if(c_tx>totalTx){// 超過了
							c_tx = totalTx;
							totalTx=0;
						}else{	// 還夠載
							totalTx-=c_tx;
						}
						d_tx = (KK_RES_D>=d? d: KK_RES_D);
						if(d_tx>totalTx){// 超過了
							d_tx = totalTx;
							totalTx=0;
						}else{	// 還夠載
							totalTx-=d_tx;
						}
					}

					gm.log('送出: {0}, {1}, {2}', m_tx, c_tx, d_tx);

					// 紀錄要此星球要載多少
					$j.cookie('KK_RES_M_TX', m_tx);
					$j.cookie('KK_RES_C_TX', c_tx);
					$j.cookie('KK_RES_D_TX', d_tx);

					// 計算剩餘總數
					KK_RES_M -= m_tx;
					KK_RES_C -= c_tx;
					KK_RES_D -= d_tx;

					// 填回輸入欄位
					$j('#KK_RES_M').get(0).value = Math.ceil(KK_RES_M/1000);
					$j('#KK_RES_C').get(0).value = Math.ceil(KK_RES_C/1000);
					$j('#KK_RES_D').get(0).value = Math.ceil(KK_RES_D/1000);
					$j.cookie('KK_RES_M', $j('#KK_RES_M').get(0).value);
					$j.cookie('KK_RES_C', $j('#KK_RES_C').get(0).value);
					$j.cookie('KK_RES_D', $j('#KK_RES_D').get(0).value);

				} break;
			}// switch
		}

		// 檢查是否自己送自己
		function sendToMyself(){
			var me = MyPlanets.coord( $j('td.header select').get(0).selectedIndex );
			var target = MyPlanets.stringToCoord( $j.cookie('KK_TARGET_PLANET') );
			return ( MyPlanets.coordCompare(me, target) );
		}

		// 移除目前星球, 移轉至下一星球
		function gotoNextPlanet(removeFirst){	// return: true-已移轉; false-未移轉
			// 移除目前星球
			if(removeFirst){
				KK_PLANET_LIST.shift();
				$j.cookie('KK_PLANET_LIST', KK_PLANET_LIST.toString());	// set cookie
				gm.log('KK_PLANET_LIST={0}', KK_PLANET_LIST.toString());
			}
			// 移轉至下一星球
			var pid = KK_PLANET_LIST[0];
			if(pid){
				window.location = $j('td.header option').get(pid).value;
				return true;
			}
			return false;
		}


		function flotten1(){
			switch(KK_FLEET_BATCH_TASK){
				case BATCH_TASK.ONE_2_MULTI:{
					// 列出星球清單
					showPlanetList($j('table[width="519"] tbody').get(0));
				} break;
				case BATCH_TASK.MULTI_2_ONE:{
					// 列出星球清單
					showPlanetList($j('table[width="519"] tbody').get(0));
					if(KK_PLANET_LIST.length>0){
						// 目前星球不為第一個選取者, 若不是則移轉
						var pid = KK_PLANET_LIST[0];
						if(pid && !$j('td.header option').get(pid).selected){
							if(gotoNextPlanet()) return;	// 要return, 否則會往下做
						}
						// 自己送自己, 移除自己並移轉
						if((KK_RES_M+KK_RES_C+KK_RES_D)>0 && sendToMyself()){
							setFleets();	// 設定艦隊 => 才會扣除自己的資源數
							if(gotoNextPlanet(true)) return;	// 要return, 否則仍會往下做
						}
					}
				} break;
			}

			// 設定艦隊
			setFleets();

			// 計算設定之艦隊數
			var totalships=0;
			$j.each( $j('input[name^="ship"]'), function(i, s){
				totalships += parseInt(s.value);
			});

			// 批次任務: 判斷是否移轉? 無艦隊, 或資源<2K
			if(KK_FLEET_BATCH_TASK>0){
				switch(KK_FLEET_BATCH_TASK){
					case BATCH_TASK.MULTI_2_ONE:{
						// 無艦隊, 或資源<2K
						if((KK_RES_M+KK_RES_C+KK_RES_D)>0 &&
								(totalships==0 || (totalships==1 && TX_RES_TOTAL<2000))
						){
							if(gotoNextPlanet(true)) return;	// 要return, 否則仍會往下做一點
						}
					} break;
				}
				// 確保艦隊數>1, 以符合自動發送條件
				if(KK_PLANET_LIST.length>0)	totalships++;
			}

			// 自動發送: 艦隊數需>1
			gm.log('totalships={0}', totalships);
			gm.log(KK_PLANET_LIST);
			if(KK_AUTO_SUBMIT && totalships>1){
				setTimeout(function(){
					// check cookie again
					if($j.cookie('KK_AUTO_SUBMIT')=='1')
						gm.Html.submit($j('form[action*="page=flotten2"]').get(0));
				}, 0);
			}

			// ----若仍停留本頁, 則做下列工作 --------------------------
			// 調整時間
			adjustTime();

			// 加入 min 按鈕
			$j.each( $j('a[href*="maxShip"]'), function(i, a){
				var matches = a.href.match(/ship\d+/);
				if(!matches) return;
				var name = matches[0];
				$j(a).after('<a id="min_'+name+'" href="#" tag="'+name+'"> (min)</a>');
				$j('a#min_'+name).click(function(){
					$j('input[name="'+$j(this).attr('tag')+'"]').get(0).value=0;
				});
			});

			// 紀錄改變船艦數
			$j('input[name^="ship"]').change(function(){
				// set cookie
				gm.log('{0}', this.name);
				$j.cookie('KK_'+this.name, this.value);	// eg. KK_ship202
			});

			// 以名稱取代坐標
			$j.each( $j('a[href*="page=galaxy"]'), function(i, a){
				var name = MyPlanets.getNameByCoord($j.trim(a.innerHTML));
				if(name != ''){
					a.innerHTML = name;
				}
			});
		}

		function flotten2(){
			// 移除第一個選取星球
			var planetId=-1;
			if(KK_FLEET_BATCH_TASK>0 && KK_PLANET_LIST.length>0){
				planetId = parseInt(KK_PLANET_LIST.shift());
				gm.log('planetId={0}', planetId);
				// set cookie
				$j.cookie('KK_PLANET_LIST', KK_PLANET_LIST.toString());
				gm.log('KK_PLANET_LIST={0}', KK_PLANET_LIST.toString());
			}

			// 設定目標星球(if any)
			var target=null;
			if(KK_FLEET_BATCH_TASK==BATCH_TASK.ONE_2_MULTI)
				target = MyPlanets.coord(planetId);
			else // 沿用前次目的星球
				target = MyPlanets.stringToCoord( $j.cookie('KK_TARGET_PLANET') );
			if(target){
				$j('select[name="planettype"]').get(0).value = target.type;
				$j('input[name="galaxy"]').get(0).value = target.galaxy;
				$j('input[name="system"]').get(0).value = target.system;
				$j('input[name="planet"]').get(0).value = target.planet;
			}

			// read cookie: KK_FLEET_SPEED
			var KK_FLEET_SPEED = $j.cookie('KK_FLEET_SPEED');
			if(KK_FLEET_SPEED){
				$j('select[name="speed"]').get(0).value = parseInt(KK_FLEET_SPEED);
			}

			// (Note) after reading cookie, shortInfo() should be called to refresh data
			shortInfo();

			// save cookie: planet, speed
			$j('input[type="submit"]').click(function(){
				// planet coord
				$j.cookie('KK_TARGET_PLANET',
					$j('select[name="planettype"]').get(0).value + ',' +
					$j('input[name="galaxy"]').get(0).value + ':' +
					$j('input[name="system"]').get(0).value + ':' +
					$j('input[name="planet"]').get(0).value
				);
				// speed
				$j.cookie('KK_FLEET_SPEED', $j('select[name="speed"]').get(0).value);
			});

			// submit automatically
			if(KK_AUTO_SUBMIT)
				gm.Html.submit($j('form[action*="page=flotten3"]').get(0));

		}

		function flotten3(){
			// 設定資源量
			switch(KK_FLEET_BY){
				case FLEET_BY.RES_INPUT:{　// 輸入
					var m = parseInt($j.cookie('KK_RES_M_TX'));
					var c = parseInt($j.cookie('KK_RES_C_TX'));
					var d = parseInt($j.cookie('KK_RES_D_TX'));
					$j('input[name="resource1"]').get(0).value=m;
					$j('input[name="resource2"]').get(0).value=c;
					$j('input[name="resource3"]').get(0).value=d;
				} break;
				default: {	// 勾選
					if(KK_CHK_M)	maxResource('1');
					if(KK_CHK_C)	maxResource('2');
					if(KK_CHK_D)	maxResource('3');
				} break;
			}

			// insert javascript code
			function zeroResource(id){	// id=1,2,3
				if(id){
					$j('input[name="resource'+id+'"]').get(0).value=0;
				}else{
					$j('input[name="resource1"]').get(0).value=0;
					$j('input[name="resource2"]').get(0).value=0;
					$j('input[name="resource3"]').get(0).value=0;
				}
			}
			var js = zeroResource.toString();
			gm.Dom.js(js);

			// add 0% for each resource
			var as = $j('a[href*="maxResource"]');
			//alert(as.length);
			$j.each(as, function(i, a){
				a.innerHTML = '100%';
				var b = a.cloneNode(true);
				b.href = a.href.replace('max', 'zero').replace('Resources', 'Resource');
				b.innerHTML = '0%';
				$j(a).after($j(b));
				$j(a).after(' | ');
			});

			// 是否自動送出表單?
			if(KK_FLEET_TASK>0){
				// 若有此種任務則選擇, 並自動送出表單
				var rdo = $j('input[type="radio"][value="'+ KK_FLEET_TASK +'"]').get(0);
				if(rdo){
					rdo.checked = true;
					gm.Html.submit($j('form').get(0));
				}
			}

		}

		function b_building(){
		}

		function buildings(){	// 造船廠
			if(!KK_AUTO_MAKE_SHIP)	return;

			// 列出星球清單
			showPlanetList($j('table[width="468"] tbody').get(0));

			if(KK_PLANET_LIST.length>0){
				// 目前星球不為第一個選取者, 若不是則移轉
				var pid = KK_PLANET_LIST[0];
				if(pid && !$j('td.header option').get(pid).selected){
					if(gotoNextPlanet()) return;	// 要return, 否則會往下做
				}

				// 移除第一個選取星球
				pid = parseInt(KK_PLANET_LIST.shift());
				// set cookie
				$j.cookie('KK_PLANET_LIST', KK_PLANET_LIST.toString());
				gm.log('KK_PLANET_LIST={0}', KK_PLANET_LIST.toString());

				// KK_SHIP_TYPE
				if(KK_SHIP_TYPE>0){
					var textbox = $j('input[name="fmenge['+KK_SHIP_TYPE+']"]').get(0);
					if(textbox){
						textbox.value = 999;
					}
				}

				// submit automatically
				gm.Html.submit($j('form[action*="page=buildings"]').get(0));
			}
		}

		function resources(){
			function setTo100(e){
				var sels = $j('select[name*="last"]');
				$j.each(sels, function(i, s){
					s.selectedIndex = 0;
				});
				// submit the form
				gm.Html.submit($j('form[id="ressourcen"]').get(0));
			}

			function setTo0(e){
				// set buttonAll0 select items to 100%
				var sels = $j('select[name*="last"]');
				$j.each(sels, function(i, s){
					s.selectedIndex = 10;
				});
				// submit the form
				gm.Html.submit($j('form[id="ressourcen"]').get(0));
			}

			// reset to 100% if all 0%
			var sels = $j('select[name^="last"]');
			if(sels.length>0){
				var all0=true;
				$j.each(sels, function(i, s){
					if(s.name != 'last212' && s.selectedIndex != 10) all0=false;
				});
				if(all0)	setTo100();
			}

			// inset 100% and 0% button
			var inputCalc = $j('input[name="action"]');
			if(inputCalc){
				// 100%
				var buttonAll = $j('button').get(0);
				buttonAll.innerHTML = '100%';
				$j(buttonAll).insertAfter(inputCalc);
				buttonAll.addEventListener('click', setTo100, true);

				// 0%
				var buttonAll0 = $j('button').get(0);
				buttonAll0.innerHTML = '0%';
				$j(buttonAll0).insertAfter(inputCalc);
				buttonAll0.addEventListener('click', setTo0, true);

				// <br>
				$j(inputCalc).after('<br>');
			}

		}

		function options(){
			// vacation mode, reset all passwords
			$j('input[name="urlaubs_modus"]').click(function(){
				$j('input[name="db_password"]').get(0).value='';
				$j('input[name="newpass1"]').get(0).value='';
				$j('input[name="newpass2"]').get(0).value='';
			});
		}

		function statistics(){
		  // 加入搜尋連結
      $j.each($j('th:first-child + th'), function(i,th){
        var userid = $j.trim(th.innerHTML);
        var a = $j('a', th).get(0);
        if(a)  userid = $j.trim(a.innerHTML);
        $j(th).append(' <a target=_blank href="index.php?page=suche&userid='+userid+'&session='+SESSION_ID+'">-></a>');
        $j(th).append(' <input id="get_'+userid+'" type="button" value="scan">');
			});

			function ajaxOnSuche(html, th){
				var div = gm.Dom.insertHddenHtml(html);
				try{
					var a = $j('#content a[href*="page=galaxy"]', div).get(0);
					if(a){
						$j(a).attr('target', '_blank');
						$j(th).append(a);
					}
				}finally{ $j(div).remove();	}
			}

      $j('input[id^="get_"]').click(function(){
				var th = $j('th', this.parentNode.parentNode).get(2);
				var userid = this.id.replace('get_', '');
				//http://uni24.ogame.org/game/index.php?page=suche&session=c50bf9e56fdf&type=playername&searchtext=abc
				var url = 'index.php?page=suche&session='+SESSION_ID+'&type=playername&searchtext='+userid;
				$j.get(url,	function(html){
					ajaxOnSuche(gm.Html.getHtmlBody(html), th);
				});
				$j(this).hide();
      });


		  // 加入過濾按鈕
		  var t = $j('#content td').get(0);
      $j(t).append('<input id="all" type="button" value="全部"> ' +
        '<input id="noalli" type="button" value="無盟"> ' +
        '<input id="scanNoalli" type="button" value="掃瞄無盟坐標">');

      $j('#all').click(function(){
        $j.each($j('#content a[target="_ally"]'), function(i,a){
           var tr = a.parentNode.parentNode;
            $j(tr).show();
        });
      });

      $j('#noalli').click(function(){
        $j.each($j('#content a[target="_ally"], #content a[href*="page=allianzen"]'), function(i,a){
          var tr = a.parentNode.parentNode;
					if($j.trim(a.innerHTML) == ''){
						$j(tr).addClass('noalliance');
					}else{
						$j(tr).hide();
					}
        });
      });

      $j('#scanNoalli').click(function(){
				$j.each( $j('tr.noalliance input[id^="get_"]'), function(i, btn){
					$j(btn).click();
				});
      });

		}

		function suche(){
		  var userid = gm.url_params.userid;
		  if(userid){
		    $j('input[name="searchtext"]').get(0).value = $j.trim(userid);
        // submit the form
			  gm.Html.submit($j('form').get(0));
			}
		}

		// ---------------------------------------------------------------------------

		init();

		if(/page\=galaxy/.test(gm.url)){
			galaxy();
		}

		if(/page\=overview/.test(gm.url)){
			overview();
		}

		if(/page\=messages/.test(gm.url)){
			messages();
		}

		if(/page\=flotten1/.test(gm.url)){
			flotten1();
		}

		if(/page\=flotten2/.test(gm.url)){
			flotten2();
		}

		if(/page\=flotten3/.test(gm.url)){
			flotten3();
		}

		if(/page\=buildings/.test(gm.url)){
			buildings();
		}

		if(/page\=b_building/.test(gm.url)){
			b_building();
		}

		if(/page\=resources/.test(gm.url)){
			resources();
		}

		if(/page\=options/.test(gm.url)){
			options();
		}

		if(/page\=statistics/.test(gm.url)){
			statistics();
		}

		if(/page\=suche/.test(gm.url)){
			suche();
		}

	}

	// public
	return {
		version: '2008.4.23',
		// ---------------------------------------------------------------------------
		// 由此啟動
		// ---------------------------------------------------------------------------
		main: function(f){	// 注意: 不可直接傳入 GM_xmlhttpRequest, 會導致 permittion error
			gm.log('OGAME v{0}', this.version);

			_getHtml = f;

			_main();
		}
	};

}();



Number.prototype.addDot = function(){
	var s = this.toString();
	var l = s.length;
	if(l<=3)
		return s;
	else{
		if(l>6){	// 二個.
			s = s.substring(0, l-6) + '.' + s.substring(l-6, l);
			l++;
		}
		return s.substring(0, l-3) + '.' + s.substring(l-3, l);
	}
};

String.prototype.removeDot = function(){
	return this.replace(/\./g, '');
};

const DT_TYPE = {
	SECOND: 1,
	MINUTE: 2,
	HOUR: 3,
	DAY: 4,
	MONTH: 5,
	YEAR: 6,
	QTR: 7
};
